/**
 * 用户管理路由
 */
import React, {Component} from 'react'
import { Card, Button, Table, Modal, message } from 'antd'
import UserForm from './components/user-form'
import {formatDate} from '../../../../utils/dateUtils'
import LinkButton from '../../../../components/link-button/LinkButton'
import {reqUserList, reqDeleteUser, reqAddOrUpdateUser} from '../../../../api'

export default class User extends Component {

    state = {
        users: [], // 所有用户列表
        roles: [], // 所有角色列表
        isShow: false, // 是否显示确认框
    }
    initColumns = ()=>{
        this.columns = [
            {
                title: '用户名',
                dataIndex: 'username'
            },
            {
                title: '邮箱',
                dataIndex: 'email',
            },
            {
                title: '电话',
                dataIndex: 'phone',
            },
            {
                title: '注册时间',
                dataIndex: 'create_time',
                // render: (time) => formatDate(time)
                render: formatDate
            },
            {
                title: '所属角色',
                dataIndex: 'role_id',
                /*render: (role_id)=>{
                    return this.state.roles.find(role=>role._id===role_id).name
                    // const roles = this.state.roles
                    // for(let i=0; i<roles.length; i++) {
                    //     if(roles[i]._id===role_id) {
                    //         return <span>{roles[i].name}</span>
                    //     }
                    // }
                    // return null
                }*/
                render: (role_id)=>this.roleNames[role_id]
            },
            {
                title: '操作',
                render: (user)=>{
                    return (
                        <span>
                            <LinkButton onClick={()=>this.showUpdate(user)}>修改</LinkButton>
                            <LinkButton onClick={()=>this.deleteUser(user)}>删除</LinkButton>
                        </span>
                    )
                }
            }
        ]
    }

    getUserList = async ()=>{
        const result = await reqUserList()
        if(result.status===0) {
            const {users, roles} = result.data
            this.initRoleNames(roles)
            this.setState({
                users,
                roles
            })
        }
    }

    // 根据role的数组, 生成包含所有角色名的对象(属性名用角色id值)
    initRoleNames = (roles) => {
        const roleNames = roles.reduce((pre, role)=>{
            pre[role._id] = role.name
            return pre
        }, {})
        this.roleNames = roleNames
    }

    // 显示修改界面
    showUpdate = (user)=>{
        this.user = user
        this.setState({
            isShow: true
        })
    }
    // 显示添加界面
    showAdd = ()=>{
        this.user = null  // 去除前面保存的user
        this.setState({isShow: true})
    }

    // 删除指定用户
    deleteUser = (user)=>{
        Modal.confirm({
            title: `确认删除${user.username}吗?`,
            onOk: async ()=>{
                const result = await reqDeleteUser(user._id)
                if(result.status===0) {
                    message.success('删除用户成功!')
                    this.getUserList()
                }
            }
        })
    }

    // 添加/更新用户
    addOrUpdateUser = ()=>{
        this.form.validateFields(async (error,values)=>{
            if(!error) {
                this.setState({isShow: false})

                // 1. 收集输入数据
                const user = values
                this.form.resetFields()
                if(this.user) {  // 如果是更新, 需要给user指定_id属性
                    user._id = this.user._id
                }

                // 2. 提交添加的请求
                const result = await reqAddOrUpdateUser(user)

                // 3. 更新列表显示
                if(result.status===0) {
                    message.success(`${this.user ? '修改' : '添加'}用户成功`)
                    this.getUserList()
                }
            }
        })
    }

    UNSAFE_componentWillMount() {
        this.initColumns()
    }
    componentDidMount() {
        this.getUserList()
    }

    render() {
        const {users, roles, isShow} = this.state
        const user = this.user || {}

        const title = <Button type="primary" onClick={this.showAdd}>创建用户</Button>
        return (
            <Card title={title}>
                <Table bordered rowKey="_id" dataSource={users} columns={this.columns}
                       pagination={{
                           defaultPageSize: 5, defaultCurrent: 1,
                           showSizeChanger:true, pageSizeOptions: ['5','10','20','40'],
                           showQuickJumper: true
                       }}/>

                <Modal title={user._id ? '修改用户' : '添加用户'}
                       visible={isShow} onOk={this.addOrUpdateUser}
                       onCancel={()=>{
                           this.setState({ isShow: false })
                           this.form.resetFields()
                       }}
                >
                    <UserForm roles={roles} user={user} setForm={(form)=>this.form=form}/>
                </Modal>
            </Card>
        )
    }
}
